package com.sxf.controller.blog.admin;

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sxf.common.tools.CommonTools;
import com.sxf.common.tools.Constants;
import com.sxf.controller.SuperController;
import com.sxf.controller.blog.FileController;
import com.sxf.domain.Post;
import com.sxf.domain.PostMeta;
import com.sxf.domain.PostVO;
import com.sxf.domain.UserVO;
import com.sxf.formbean.PostForm;
import com.sxf.mybatis.page.Pagination;
import com.sxf.querybean.PostQuery;
import com.sxf.service.PostService;
import com.sxf.view.datatables.DataTables;
import com.sxf.view.datatables.DatatablesHelp;

/**
 * 多媒体管理
 * 
 * @author phsxf
 * 
 */
@Controller
@DependsOn(value = { "fileController" })
@RequestMapping("blog/admin/media")
public class MediaController extends SuperController {
	@Resource(name = "postService")
	private PostService postService;
	@Resource(name = "fileController")
	private FileController fileController;

	@RequestMapping("")
	public ModelAndView toIndex() throws Exception {
		ModelAndView mav = new ModelAndView();
		return mav;
	}

	@RequestMapping("/listAjax")
	@ResponseBody
	public Pagination<PostVO> listAjax(
			@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows,
			WebRequest request) throws Exception {
		PostQuery query = new PostQuery();
		String dtjson = request.getParameter("dtjson");
		if (StringUtils.isNotBlank(dtjson)) {
			DataTables dt = DatatablesHelp.getDataTable(dtjson);
			String name = dt.getSearch();
			if (StringUtils.isNotBlank(name)) {
				query.setTitle(name);
			}
		}
		query.setStatus(Constants.POST_STATUS_INHERIT);
		query.setType(Constants.POST_TYPE_ATTACHMENT);
		Pagination<PostVO> pages = postService.queryPage(query);
		return pages;
	}

	/**
	 * @param postId
	 *            文章编号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toAdd")
	public ModelAndView toAdd() throws Exception {
		ModelAndView mav = new ModelAndView("blog/admin/media_add");
		mav.addObject("user", getCurrentUser());

		return mav;
	}

	@RequestMapping("/doAdd")
	public ModelAndView doAdd(
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "file") MultipartFile file,
			HttpServletRequest request) throws Exception {
		ModelAndView mav = new ModelAndView("redirect:/blog/admin/media");
		UserVO user = getCurrentUser();
		mav.addObject("user", user);
		fileController.oneFileUpload(name, file);// 上传文件
		if (file != null && !file.isEmpty()) {
			Post post = new Post();
			Date d = new Date();
			post.setAuthor(user.getId());
			post.setPassword("");
			post.setMenuOrder(0);
			post.setCommentCount(0l);
			post.setPinged("");
			post.setContentFiltered("");
			post.setDate(d);
			post.setDateGmt(CommonTools.getGMT0(d));
			post.setModified(d);
			post.setModifiedGmt(CommonTools.getGMT0(d));
			post.setType(Constants.POST_TYPE_ATTACHMENT);
			post.setStatus(Constants.POST_STATUS_INHERIT);
			post.setMimeType(file.getContentType());
			String fileName = file.getOriginalFilename();
			post.setName(file.getOriginalFilename());
			post.setContent("");
			post.setTitle(fileName.substring(0, fileName.lastIndexOf(".")));
			post.setExcerpt("");
			post.setToPing("");
			postService.insert(post);// 插入
			if (post.getId() != null) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
				Post updatePost = new Post();
				updatePost.setId(post.getId());
				StringBuilder sb = new StringBuilder();
				sb.append("http://");
				sb.append(request.getLocalAddr());
				if (request.getLocalPort() != 80) {
					sb.append(":");
					sb.append(request.getLocalPort());
				}
				sb.append(request.getContextPath());
				sb.append("/upload/");
				sb.append(sdf.format(d));
				sb.append("/");

				sb.append(file.getOriginalFilename());
				updatePost.setGuid(sb.toString());
				postService.update(updatePost);
			}
		}
		return mav;
	}

	/**
	 * @param postId
	 *            文章编号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	public ModelAndView toEdit(
			@RequestParam(value = "postId", required = true) Long postId)
			throws Exception {
		ModelAndView mav = new ModelAndView("blog/admin/media_edit");
		mav.addObject("user", getCurrentUser());
		if (postId != null) {
			PostQuery pq = new PostQuery();
			pq.setType(Constants.POST_TYPE_ATTACHMENT);
			pq.setId(postId);
			pq.setQueryAllColumn(true);
			PostVO post = postService.queryOne(pq);
			if (post != null) {
				mav.addObject("post", post);
			}
		}
		return mav;
	}

	@RequestMapping("/doEdit")
	public ModelAndView doEdit(@Valid @ModelAttribute PostForm pF,
			BindingResult br, WebRequest request) throws Exception {
		ModelAndView mav = new ModelAndView();
		if (br.hasErrors()) {
			if (pF.getId() != null) {

			}
		}
		if (pF != null) {
			Post post = new Post();
			BeanUtils.copyProperties(pF, post);
			int i = 0;
			if (post.getId() != null) {
				Date d = new Date();
				post.setModified(d);
				post.setModifiedGmt(CommonTools.getGMT0(d));
				i = postService.update(post);// 更新
			}
			if (i > 0) {
				Long postId = post.getId();
				mav.setViewName("forward:/blog/admin/media/edit?postId="
						+ postId);
			}
		}

		return mav;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public String delete(@RequestParam(required = true) Long postId,
			WebRequest request) throws Exception {
		if (postId != null) {
			PostQuery pq = new PostQuery();
			pq.setId(postId);
			pq.setQueryAllColumn(true);
			Post post = postService.queryOne(pq);
			if (post != null
					&& Constants.POST_TYPE_ATTACHMENT.equals(post.getType())) {
				postService.delete(post);
				boolean isDeleteFile = false;
				if (isDeleteFile) {
					deleteFile(post.getDate(), post.getName());
				}

			}

			PostMeta pm = new PostMeta();
			pm.setPostId(postId);
			postService.deletePostMeta(pm);
		}
		return "success";
	}

	/**
	 * 删除文件
	 * 
	 * @param d
	 *            创建日期
	 * @param fileName
	 *            文件名
	 * @return
	 * @throws Exception
	 */
	private boolean deleteFile(Date d, String fileName) throws Exception {
		URL url = Thread.currentThread().getContextClassLoader()
				.getResource("");
		URI uri = url.toURI();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
		File directory = new File(new URI(uri.toString() + "../../upload/"
				+ sdf.format(new Date())));
		String path = directory.getCanonicalPath();
		File file = new File(path + File.separator + fileName);
		if (file.exists()) {
			return file.delete();
		}
		return false;
	}
}